package org.ngmj.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class HelloServer {
    public static void main(String[] args) {
        // 创建一个 ServerBootstrap 对象，它是 Netty 用于启动服务器端的辅助启动类，
        new ServerBootstrap()
                // 创建一个 NioEventLoopGroup 对象，它是 Netty 用于处理 I/O 操作的线程组，
                // 用于处理客户端的连接和 I/O 操作
                .group(new NioEventLoopGroup())
                // 指定 NioServerSocketChannel，使用Nio服务端通道，
                .channel(NioServerSocketChannel.class)
                // BOSS处理连接 worker处理读写
                .childHandler(
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel nsc) throws Exception {
                                nsc.pipeline().addLast(new StringDecoder());
                                nsc.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println(msg);
                                        super.channelRead(ctx, msg);
                                    }
                                });
                            }
                        })
                .bind(8080);
    }
}
